const gulp = require("gulp");
const concat = require("gulp-concat");
const uglify = require("gulp-uglify");
const replace = require("gulp-replace");
const babel = require("gulp-babel");
const browserSync = require("browser-sync").create();

// 合并和压缩 JavaScript 文件
gulp.task("scripts", () =>
  gulp
    .src(["src/js/*.js", "src/libs/*.js", "src/main.js"])
    .pipe(concat("bundle.js"))
    .pipe(babel({ presets: ["@babel/preset-env"] })) // 使用 Babel 转换
    .pipe(uglify())
    .pipe(gulp.dest("dist"))
    .pipe(browserSync.stream())
);

// 打包 HTML 文件，只保留 bundle.js
gulp.task("html", () =>
  gulp
    .src("src/index.html")
    .pipe(replace(/<script.*><\/script>/g, "")) // 移除所有 script 标签
    .pipe(replace(/<\/body>/, '<script src="bundle.js"></script>\n</body>')) // 添加 bundle.js
    .pipe(gulp.dest("dist"))
);

// 复制 CSS 文件到 dist 目录
gulp.task("css", () =>
  gulp.src("src/main.css").pipe(gulp.dest("dist")).pipe(browserSync.stream())
);

// 复制图片和其他静态资源到 dist 目录
gulp.task("public", () =>
  gulp
    .src("public/**/*")
    .pipe(gulp.dest("dist/public"))
    .pipe(browserSync.stream())
);

// 监听文件变化，自动刷新浏览器
gulp.task("watch", function () {
  browserSync.init({
    server: {
      baseDir: "./dist",
    },
  });

  gulp.watch("src/main.css", gulp.series("css"));
  gulp.watch(
    ["src/js/**/*.js", "src/libs/*.js", "src/main.js"],
    gulp.series("scripts")
  );
  gulp.watch("src/index.html", gulp.series("html"));
  gulp.watch("public/**/*", gulp.series("public"));
});

// 默认任务
gulp.task(
  "default",
  gulp.parallel("css", "scripts", "html", "public", "watch")
);
